<?php

define('IN_ECTOUCH', true);

require(dirname(__FILE__) . '/include/init.php');
require(ROOT_PATH . 'include/lib_weixintong.php');
if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}

$affiliate = unserialize($GLOBALS['_CFG']['affiliate']);
$smarty->assign('affiliate', $affiliate);

/*------------------------------------------------------ */
//-- INPUT
/*------------------------------------------------------ */

if (empty($_REQUEST['act']))
{
    $act = 'list';
}
else
{
	$act=$_REQUEST['act'];
}
if ($_REQUEST['act'] == 'raffle')
{       require(ROOT_PATH . 'include/cls_json.php');
	    $json   = new JSON;
				
		//登录状态
	    if ($_SESSION['user_id'] > 0)
    	{
            $sql = "SELECT apply_sale FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id='".$_SESSION['user_id'] ."'";
            $result = $GLOBALS['db']->getOne($sql);
            //用户抽奖1为已抽奖
            if($result==1){
            	$result=array(
					'status'=>'2',
					'con'=>'每人只有一次机会哦，去主会场发现更多优惠吧',
					'num'=>0
			    );
            //未中奖，抽奖中
            }else{
            	$sql="select * from ".$GLOBALS['ecs']->table('lottery');
	            $row = $GLOBALS['db']->getAll($sql);
            	$conment=get_rand($row);
                $num = ReduceNumber($conment['id'], $_SESSION['user_id'] ,$conment['name'] ,$conment['num']);
	                if($num['status']==0){
	                	$result=array(
								'status'=>'5',
								'con'=>'恭喜你抽中 黄金卡 ，请及时完善您的收货地址',
								'num'=>1
						     );
	                }elseif($conment['id']==6){
		                        $result=array(
									'status'=>'3',
									'con'=>'遗憾与大奖擦身而过，去主会场发现更多优惠吧',
									'num'=>6
							     );

			        }else{
		                        $result=array(
									'status'=>'4',
									'con'=>"恭喜你抽中".$conment['name']."，请及时完善您的收货地址",
									'num'=>$conment[id]
							     );

			        }
	        }
	                 
            
        //未登录状态
    	}else{
	        
	        $result=array(
					'status'=>'1',
					'con'=>'请先登录或注册后再来抽奖',
					'num'=>0
			);

    	}

	    die($json->encode($result));

}


/**
 *中奖了,,减少库存,,加入中奖列表,返回0表示抽奖完毕了
*/
function ReduceNumber($id, $user_id ,$liname ,$linum )
{
	//先检查库存是否正确
	$sql = "select * from ".$GLOBALS['ecs']->table('lottery')." where id='".$id."' and (total-outnum)>0 and status=1";
	$num = $GLOBALS['db']->getOne($sql);
	
	if($num)
	{   
		//增加已抽取奖品数
		$sql1 = "update ".$GLOBALS['ecs']->table('lottery')." set outnum=outnum+1 where id='".$id."'";
		$GLOBALS['db']->query($sql1);

		//增加中奖用户
		$sql2 = "insert into ".$GLOBALS['ecs']->table('lottery_user')." (lid, user_id, user_name, status, number,prize,wintime) values('".$id."','".$user_id."','".$_SESSION['user_name']."','0','".$linum."','".$liname."','".local_strtotime(date("Y-m-d H:i:s", time()+8*3600))."')";
		$GLOBALS['db']->query($sql2);
		$id = $GLOBALS['db']->insert_id();

        //改变用户抽奖状态
		$sql3 = "update ".$GLOBALS['ecs']->table('users')." set apply_sale=1 where user_id='".$_SESSION['user_id'] ."'";
        $GLOBALS['db']->query($sql3);


		//是否还有抽奖数量
		$sql = "select 1 from ".$GLOBALS['ecs']->table('lottery')." where id='".$id."' and total=outnum";
		$num = $GLOBALS['db']->getOne($sql);
		if($num)
		{
			$sql = "update ".$GLOBALS['ecs']->table('lottery')." set status=2 where id='".$id."'";
			$GLOBALS['db']->query($sql);
		}
		$result = array('status' => 1,'id' => $id);
		return $result;
	}
	else
	{
		//增加已抽取奖品数
		$sql1 = "update ".$GLOBALS['ecs']->table('lottery')." set outnum=outnum+1 where id='1'";
		$GLOBALS['db']->query($sql1);


		//增加中奖用户
		$sql2 = "insert into ".$GLOBALS['ecs']->table('lottery_user')." (lid, user_id, user_name, status, number,prize,wintime) values('1','".$user_id."','".$_SESSION['user_name']."','0','".$linum."','黄金卡','".local_strtotime(date("Y-m-d H:i:s", time()+8*3600))."')";
		$GLOBALS['db']->query($sql2);
		$id = $GLOBALS['db']->insert_id();

        //改变用户抽奖状态
		$sql3 = "update ".$GLOBALS['ecs']->table('users')." set apply_sale=1 where user_id='".$_SESSION['user_id'] ."'";
        $GLOBALS['db']->query($sql3);

		$result = array('status' => 0,'id' => 1);
		return $result;
	}
	
}

/**
 *中奖概率计算
*/


function get_rand($prize_arr)
{   
	$proSum = 1000;
	foreach ($prize_arr as $key => $value) {
		$randNum=mt_rand(1, $proSum);
		if($randNum <= $value['lg_pro']){
           $result  = array('id' =>$value['id'] , 'name' =>$value['lg_name'] , 'num' =>$randNum);
           break;
		}else{
			$proSum -= $value['lg_pro'];
		}
	}

   return $result;
}

/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */
$cache_id = sprintf('%X', crc32($_SESSION['user_rank'] . '-' . $_CFG['lang']));
if (!$smarty->is_cached('lottery.dwt', $cache_id))
{   
    $smarty->assign('image_width',  $_CFG['image_width']);
    $smarty->assign('image_height', $_CFG['image_height']);
    $smarty->assign('helps',        get_shop_help()); // 网店帮助
    $smarty->assign('id',           $goods_id);
    $smarty->assign('type',         0);
    $smarty->assign('cfg',          $_CFG);
    $smarty->assign('promotion',       get_promotion_info($goods_id));//促销信息
    $smarty->assign('promotion_info', get_promotion_info());
	
	 $sql = 'SELECT user_name, prize ,tel FROM ' . $ecs->table('lottery_user') . 
	 ' where lid <> 6 ORDER BY wintime DESC limit 8 ';
     $lotteryList = $db->getAll($sql);
	 $smarty->assign('lotteryList',       $lotteryList);
	$smarty->display('lottery.dwt');//, $cache_id);

}


//seed用户自定义函数以微秒作为种子
function seed() 
{
list($msec, $sec) = explode(' ', microtime());
return (float) $sec;
}



?>
